// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })

const db = cloud.database()
const _ = db.command
const pay = cloud.cloudPay

// 云函数入口函数
exports.main = async event => {
  const { OPENID: _openid, ENV: envId } = cloud.getWXContext()
  if (!_openid) {
    throw new Error('no openid')
  }

  const { promotionId, casts } = event
  if (!promotionId || !casts) {
    throw new Error('missing parameters')
  }

  const {
    data: [uData],
  } = await db.collection('store').where({ _openid }).get()
  if (!uData) {
    throw new Error('no login store')
  }

  const {
    data: [promotion],
  } = await db
    .collection('promotion')
    .field({ _openid: false, audit: false })
    .where({ _id: promotionId })
    .get()

  const sIds = casts.map(v => v.screenId)
  const { data: sData } = await db
    .collection('screen')
    .where({
      _id: _.in(sIds),
    })
    .get()
  const sMap = new Map(sData.map(v => [v._id, v]))
  let cost = 0
  casts.forEach(v => {
    v.screen = sMap.get(v.screenId)
    delete v.screenId
    cost += v.weeks.length * v.screen.price
  })
  if (cost === 0) {
    cost = 0.01
  } else if (cost < 800) {
    cost = cost
  } else if (cost < 1200) {
    cost = cost * 0.875
  } else if (cost < 1600) {
    cost = cost * 0.8
  } else {
    cost = cost * 0.75
  }

  const createAt = new Date()
  const data = {
    _openid,
    promotion,
    casts,
    cost,
    status: 0,
    createAt,
  }
  const { _id: orderId } = await db.collection('order').add({ data })

  const fee = cost * 100
  const { payment } = await pay.unifiedOrder({
    body: promotion.name,
    outTradeNo: orderId,
    spbillCreateIp: '127.0.0.1',
    subMchId: '1601711849',
    totalFee: fee,
    functionName: 'update-order',
    envId,
  })
  if (!payment) {
    throw new Error('unified order failed')
  }

  await db.collection('order').doc(orderId).update({ data: { payment } })

  return { orderId, payment }
}
